package com.fire.common.util;

import com.fire.common.domain.BusinessException;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.UUID;

/**
 * 七牛云测试工具类
 * @author fire
 * @date 2021年07月17日10:04
 */
public class QiniuUtil {

    private static final Logger logger = LoggerFactory.getLogger(QiniuUtil.class);

//    提供工具类

    /**
     * 文件上传工具方法
     * @param accessKey
     * @param secretKey
     * @param bucket
     * @param bytes
     * @param fileName
     */
    public static void upload2Qiniuyun(String accessKey,String secretKey,String bucket,byte[] bytes,String fileName) throws RuntimeException{
        //构造一个带指定 Region 对象的配置类,指定存储区域
        Configuration cfg = new Configuration(Region.huabei());
//...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证，然后准备上传
//        String accessKey = "AcUYaw-bVbTVHRWVXbE4_lBQ6VJju1-VcnkwyCHQ";
//        String secretKey = "O2nTgDuc7fLFxhDwNIWtabmp2F6C7GcyFAvWfzd7";
//        String bucket = "shanju---pay";

//默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = fileName;
        try {
//            得到本地文件的字节数组
//            String filePath = "F:\\1.png";
//            FileInputStream fileInputStream = new FileInputStream(new File(filePath));
//            byte[] bytes = IOUtils.toByteArray(fileInputStream);
//            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
//            认证
            Auth auth = Auth.create(accessKey, secretKey);
//            认证通过后得到token
            String upToken = auth.uploadToken(bucket);

            try {
//                key：--》一般为一个不重复的名称
//               上传文件：参数，字节数组，token令牌
                Response response = uploadManager.put(bytes, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
            } catch (QiniuException ex) {

                Response r = ex.response;
                System.err.println(r.toString());
                logger.error("上传文件到七牛：{}",ex.getMessage());
                try {
                    logger.error(r.bodyString());
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore

                }
                throw new RuntimeException(r.bodyString());
            }
        } catch (Exception ex) {
            logger.error("上传文件到七牛：{}",ex.getMessage());
            throw new RuntimeException(ex.getMessage());
        }

    }

//    测试文件上传
    private static void testUpload(){
        //构造一个带指定 Region 对象的配置类,指定存储区域
        Configuration cfg = new Configuration(Region.huabei());
//...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证，然后准备上传
        String accessKey = "AcUYaw-bVbTVHRWVXbE4_lBQ6VJju1-VcnkwyCHQ";
        String secretKey = "O2nTgDuc7fLFxhDwNIWtabmp2F6C7GcyFAvWfzd7";
        String bucket = "shanju---pay";

//默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = UUID.randomUUID().toString()+".jpg";

        try {
//            得到本地文件的字节数组
            String filePath = "F:\\1.png";
            FileInputStream fileInputStream = new FileInputStream(new File(filePath));
            byte[] bytes = IOUtils.toByteArray(fileInputStream);
            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
//            认证
            Auth auth = Auth.create(accessKey, secretKey);
//            认证通过后得到token
            String upToken = auth.uploadToken(bucket);

            try {
//                key：--》一般为一个不重复的名称
//               上传文件：参数，字节数组，token令牌
                Response response = uploadManager.put(uploadBytes, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
                throw new RuntimeException(r.bodyString());
            }
        } catch (UnsupportedEncodingException | FileNotFoundException ex) {
            //ignore
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
